from django.shortcuts import render, redirect
from django.http import HttpResponse
from . import forms
from . import models

from django.contrib import messages
import sqlite3


def issue(request):
    if (request.method == 'POST'):
        market_form = forms.IssueForm(request.POST)
        username = request.session.get('user_name', None)
        bookname = request.POST.get('bookname')
        price = request.POST.get('price')
        major = request.POST.get('major')
        grade = request.POST.get('grade')
        qq = request.POST.get('qq')
        pic = request.POST.get('pic')
        type = request.POST.get('type')
        state = "未完成"
        new_book = models.Market()
        new_book.username = username
        new_book.bookname = bookname
        new_book.price = price
        new_book.major = major
        new_book.grade = grade
        new_book.qq = qq
        new_book.pic = pic
        new_book.type = type
        new_book.state = state
        new_book.save()
        return render(request, 'market/issuedetail.html', locals())
    market_form = forms.IssueForm()
    return render(request, 'market/issue.html', locals())


def list(request):
    booklist = models.Market.objects.filter(state="未完成")
    if (request.method == 'POST'):
        bookname = request.POST.get('name')
        booklist = models.Market.objects.filter(bookname=bookname)
    context = {'booklist': booklist}
    return render(request, 'market/list.html', context)


def buy(request, id):
    conn = sqlite3.connect('db.sqlite3')
    cur = conn.cursor()
    username = request.session.get('user_name', None)
    update_sql = "UPDATE market_market SET state = '" + username + "' WHERE id = " + str(id) + ";"
    cur.execute(update_sql)
    conn.commit()
    cur.close()
    conn.close()
    return redirect('/list/')


def personal(request):
    username = request.session.get('user_name', None)
    booklist = models.Market.objects.filter(username=username)
    bookbuy = models.Market.objects.filter(state=username)
    context = {'booklist': booklist, 'username': username, 'bookbuy': bookbuy}
    return render(request, 'market/personal.html', context)


def delete(request, id):
    username = request.session.get('user_name', None)
    now_book = models.Market.objects.get(id=id)
    if (username != now_book.username):
        return HttpResponse('you have no permission to do this!')
    elif ("未完成" != now_book.state):
        return HttpResponse('您的发布的书籍已经出售，无法删除。')
    else:
        now_book.delete()
        return redirect('/personal/')


def search(request):
    if (request.method == 'POST'):
        major = request.POST.get('major')
        grade = request.POST.get('grade')
        type = request.POST.get('type')
        booklist = models.Market.objects.filter(major=major, grade=grade, type=type)
        context = {'booklist': booklist}
        return render(request, 'market/list.html', context)
    search_form = forms.SearchForm()
    return render(request, 'market/search.html', locals())


def cart(request, id=0):
    if id != 0:
        cart_books = models.Market.objects.filter(id=id)
    cart = request.session.get('cart', [])
    if id not in cart:
        cart.append(id)
    request.session['cart'] = cart
    cart_books = models.Market.objects.filter(id__in=cart)
    total_price = 0
    for book in cart_books:
        try:
            price = float(book.price)
            total_price += price
        except (ValueError, TypeError) as e:
            print(f'Invalid price for book {book.bookname}: {book.price} ({e})')

    return render(request, 'market/cart.html', {
        'cart_books': cart_books,
        'total_price': total_price
    })


def delete1(request, id):
    cart = request.session.get('cart', [])

    if id in cart:
        cart.remove(id)
        request.session['cart'] = cart
        messages.success(request, '书籍已成功删除！')
    else:
        messages.error(request, '书籍未找到！')
    return redirect('cart')


def checkout(request):
    if request.method == 'POST':
        cart_books = request.session.get('cart_books', [])
        total_price = sum(book['price'] for book in cart_books)
        messages.success(request, '结算成功！感谢您的购买！')
        return render(request, 'market/checkout_success.html', {'cart_books': cart_books, 'total_price': total_price})

    return redirect('cart')


def cart_view(request):
    cart_books = request.session.get('cart_books', [])
    total_price = sum(book['price'] for book in cart_books)
    return render(request, 'market/cart.html', {'cart_books': cart_books, 'total_price': total_price})
